package pers.qianyu.month_202012.date_20201219.sort;

import org.junit.*;

import java.util.*;

/**
 * 归并排序练习
 *
 * @author mizzle rain
 * @date 2020-12-19 16:41
 */
public class MergeSortTest {
    private void mergeSort(int[] arr) {
        int[] temp = new int[arr.length];
        mergeSort(arr, 0, arr.length - 1, temp);
    }

    private void mergeSort(int[] arr, int left, int right, int[] temp) {
        if (left >= right) {
            return;
        }
        int mid = left + ((right - left) >> 1);
        mergeSort(arr, left, mid, temp);
        mergeSort(arr, mid + 1, right, temp);
        int p1 = left, p2 = mid + 1, k = 0;
        while (p1 <= mid && p2 <= right) {
            if (arr[p1] < arr[p2]) {
                temp[k++] = arr[p1++];
            } else {
                temp[k++] = arr[p2++];
            }
        }
        while (p1 <= mid) {
            temp[k++] = arr[p1++];
        }
        while (p2 <= right) {
            temp[k++] = arr[p2++];
        }
        k = 0;
        for (int i = left; i <= right; i++) {
            arr[i] = temp[k++];
        }
    }

    @Test
    public void testMergeSort() {
        MergeSortTest mst = new MergeSortTest();
        for (int item = 0; item < 20; item++) {
            int[] arr = new int[10];
            for (int i = 0; i < arr.length; i++) {
                arr[i] = (int) (Math.random() * 100);
            }
            System.out.println(Arrays.toString(arr));
            int[] newArr = Arrays.copyOf(arr, arr.length);
            mst.mergeSort(arr);
            Arrays.sort(newArr);
            System.out.println(Arrays.toString(arr) + "\n");
            Assert.assertArrayEquals(arr, newArr);
        }
    }
}
